package xiyili;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import xiyili.ui.Toasts;

/**
 * Created by banxi on 14-5-13.
 *
 */
public class Share {


    /**
     * 返回一个用于临时存储的.jpg文件
     * @return
     * @throws IOException
     */
	private static File createTempImageFile() throws IOException{
		String prefix = String.valueOf(System.currentTimeMillis());
		return File.createTempFile(prefix, ".jpg");
	}

    public static void shareBitmap(Bitmap bitmap, String text, String title){
         FileOutputStream fos = null;
        try {
            File tmpFile = createTempImageFile();
            fos = new FileOutputStream(tmpFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            shareFile(tmpFile, text, title);
        } catch (IOException e) {
            e.printStackTrace();
            Toasts.showFailure("保存要分享的图片失败");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void shareFile(File tmpFile, String text, String title) {
        Context ctx = G.ctxOrNull();
        if (ctx == null) {
            Log.e("doShareFile", "CTX is null");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        if (!TextUtils.isEmpty(text)) {
            intent.putExtra(Intent.EXTRA_TEXT, text);
        }
        if (!TextUtils.isEmpty(title)) {
            intent.putExtra(Intent.EXTRA_TITLE, title);
            intent.putExtra(Intent.EXTRA_SUBJECT, title);
        }
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));

        Intent chooser = Intent.createChooser(intent, "分享 via");
        ctx.startActivity(chooser);
    }
}
